package cn.deschen.biz.service.impl;

import cn.deschen.biz.domain.entity.AdTag;
import cn.deschen.biz.domain.entity.AdUnitTag;
import cn.deschen.biz.dto.unit.UnitEleDTO;
import cn.deschen.biz.mapper.AdTagMapper;
import cn.deschen.biz.service.AdTagService;
import cn.deschen.biz.service.AdUnitTagService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 兴趣 Feature 服务实现类
 * </p>
 *
 * @author deschen
 * @since 2021-06-13
 */
@Service
public class AdTagServiceImpl extends ServiceImpl<AdTagMapper, AdTag> implements AdTagService {

    @Autowired
    private AdUnitTagService unitTagService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchUnitRel(Long unitId, Collection<Long> tagIds) {
        List<AdUnitTag> unitTagList = tagIds.stream().map(tagId -> {
            AdUnitTag unitTag = new AdUnitTag();
            unitTag.setUnitId(unitId);
            unitTag.setTagId(tagId);
            return unitTag;
        }).collect(Collectors.toList());
        unitTagService.saveBatch(unitTagList);
    }

    @Override
    public List<Long> listEleIdById(Long unitId) {
        QueryWrapper<AdUnitTag> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(AdUnitTag::getUnitId, unitId);
        List<Long> tagIdList = unitTagService.list(wrapper).stream().map(AdUnitTag::getTagId).collect(Collectors.toList());
        return tagIdList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeUnitRel(Collection<Long> unitTagIds) {
        unitTagService.removeByIds(unitTagIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Long> saveBatchTag(Long unitId, Collection<UnitEleDTO> unitEleDTOS) {
        List<Long> tagIdList = new ArrayList<>();
        List<AdTag> tagList = new ArrayList<>();
        unitEleDTOS.stream().forEach(ele -> {
            if (null == ele.getEleId()) {
                AdTag tag = new AdTag();
                tag.setTagName(ele.getEleName());
                tagList.add(tag);
            } else {
                tagIdList.add(ele.getEleId());
            }
        });
        saveBatch(tagList);
        tagIdList.addAll(tagList.stream().map(AdTag::getId).collect(Collectors.toList()));
        return tagIdList;
    }
}
